package com.donger.upms.biz.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.donger.upms.api.entity.SysDept;
import com.donger.upms.api.entity.SysDeptRelation;
import com.donger.upms.biz.mapper.SysDeptMapper;
import com.donger.upms.api.service.ISysDeptRelationService;
import com.donger.upms.api.service.ISysDeptService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门管理 服务实现类
 * </p>
 *
 * @author xyx
 * @since 2019-01-12
 */
@Service("sysDeptService")
@AllArgsConstructor
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {

    private final ISysDeptRelationService sysDeptRelationService;


    /**
     * 查询子部门ID
     *
     * @param parentId 父部门ID
     * @return 子部门ID列表
     */
    @Override
    public List<Long> queryDeptIdList(Long parentId) {
        return baseMapper.queryDeptIdList(parentId);
    }

    @Override
    public List<SysDept> queryList() {
        return this.list();
    }


    @Transactional(rollbackFor = Exception.class)
    public boolean removeDeptById(Long id) {
        List<Long> collect = sysDeptRelationService.list(new LambdaQueryWrapper<SysDeptRelation>()
                .eq(SysDeptRelation::getAncestor, id)
        ).stream().map(SysDeptRelation::getDescendant)
                .collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            this.removeByIds(collect);
        }
        sysDeptRelationService.deleteAllDeptRealtion(id);
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveDept(SysDept entity) {
        super.save(entity);
        sysDeptRelationService.insertDeptRelation(entity);
        return Boolean.TRUE;
    }

    /**
     * 更新部门
     *
     * @param sysDept 部门信息
     * @return 成功、失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateDeptById(SysDept sysDept) {
        //更新部门状态
        super.updateById(sysDept);
        //更新部门关系
        SysDeptRelation relation = new SysDeptRelation();
        relation.setAncestor(sysDept.getParentId());
        relation.setDescendant(sysDept.getDeptId());
        sysDeptRelationService.updateDeptRealtion(relation);
        return Boolean.TRUE;
    }
}
